using System;

namespace ZeBobo5.LibraryHelper.Orm
{
    public sealed class OrmValues<T> : OrmValuesBase
    {
        internal OrmValues()
        {
        }

        public T CurrentValue
        {
            get
            {
                return (T) _currentValue;
            }
            set
            {
                OnFieldChanging();
                try
                {
                    OnFieldValidating(value);
                    _currentValue = value;
                    OnFieldValidated();
                    OnFieldChanged();
                }
                catch
                {
                    throw;
                }
            }
        }

        public T OriginalValue
        {
            get
            {
                return (T) _originalValue;
            }
            internal set
            {
                _originalValue = value;
            }
        }

        internal void OnFieldChanging()
        {
            if (FieldChanging != null)
            {
                FieldChanging(this, EventArgs.Empty);
            }
        }

        internal void OnFieldChanged()
        {
            if (FieldChanged != null)
            {
                FieldChanged(this, EventArgs.Empty);
            }
        }

        internal void OnFieldValidating(T valueToSet)
        {
            if (FieldValidating != null)
                FieldValidating(valueToSet);
        }

        internal void OnFieldValidated()
        {
            if (FieldValidated != null)
                FieldValidated(this, EventArgs.Empty);
        }

        internal event EventHandler FieldChanging;
        internal event EventHandler FieldChanged;
        internal event FieldChangingEventHandler FieldValidating;
        internal event EventHandler FieldValidated;

        public override string ToString()
        {
            return CurrentValue.ToString();
        }

        #region Nested type: FieldChangingEventHandler

        internal delegate void FieldChangingEventHandler(T valueToSet);

        #endregion
    }
}